﻿using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Domain.Repositories;
using Abp.Linq.Extensions;
using Abp.Runtime.Session;
using Abp.UI;
using SingleUserMall.Authorization.Users;
using SingleUserMall.Common;
using SingleUserMall.Items;
using SingleUserMall.Items.VO;
using SingleUserMall.Stores.Form;
using SingleUserMall.Stores.VO;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace SingleUserMall.Stores
{
    [AbpAuthorize]
    public class StoreAppService : SingleUserMallAppServiceBase, IStoreAppService
    {
        private readonly IRepository<Store> _storeRepository;
        private readonly IRepository<UserStoreFavorite, long> _userFavoriteStoreRepository;
        public StoreAppService(
            IRepository<Store> storeRepository, IRepository<UserStoreFavorite, long> userStoreFavoriteRepository)
        {
            _storeRepository = storeRepository;
            _userFavoriteStoreRepository = userStoreFavoriteRepository;
        }

        [AbpAllowAnonymous]
        public async Task<PagedResultDto<StoreViewVO>> GetStoresAsync(StoreViewForm form)
        {
            var stores = _storeRepository.GetAll().Where(x => x.Status == StoreVerifyStatus.Audited && x.Id != 1 && !x.IsInvalid)
                .WhereIf(!string.IsNullOrEmpty(form.Keywords), x => x.Name.Contains(form.Keywords) || x.Discription.Contains(form.Keywords));
            if (form.Option == StoreOption.Normal)
            {
                stores = stores.OrderByDescending(x => x.StoreStar).ThenByDescending(x => x.StoreTotalSale).ThenByDescending(x => x.CreationTime);
            }
            else if (form.Option == StoreOption.Star)
            {
                stores = stores.OrderBy(x => x.StoreStar).ThenByDescending(x => x.CreationTime);
            }
            else if (form.Option == StoreOption.StarDesc)
            {
                stores = stores.OrderByDescending(x => x.StoreStar).ThenByDescending(x => x.CreationTime);
            }
            else if (form.Option == StoreOption.SaleDesc)
            {
                stores = stores.OrderByDescending(x => x.StoreTotalSale).ThenByDescending(x => x.CreationTime);
            }
            else
            {
                stores = stores.OrderByDescending(x => x.StoreTotalSale).ThenByDescending(x => x.CreationTime);
            }
            return await stores.ToPagedResultDtoAsync<Store, StoreViewVO>(form, (f, vo) =>
            {
                var tempItems = ItemManager.GetItemsByStoreId(f.Id);
                vo.Items = tempItems.ToListResultDto<Item, ItemVO>();
                vo.CommentRate = f.StoreStar * 20 + "%";
            });
        }

        public async Task RegisterStoreAsync(StoreForm form)
        {
            var userId = AbpSession.GetUserId();
            var count = await _storeRepository.CountAsync(x => x.UserId == userId && (x.Status == StoreVerifyStatus.Audited || x.Status == StoreVerifyStatus.WaitAudit));
            if (count > 0)
            {
                throw new UserFriendlyException("您已提交过申请，请等待系统审核");
            }
            await _storeRepository.DeleteAsync(x => x.UserId == userId && x.Status == StoreVerifyStatus.Rejected);
            await CurrentUnitOfWork.SaveChangesAsync();
            var store = form.MapTo<Store>();
            store.UserId = userId;
            store.Status = StoreVerifyStatus.WaitAudit;
            store.IsInvalid = false;
            await _storeRepository.InsertAsync(store);
        }

        public async Task FavoriteStoreAsync(SingleId<int> form)
        {
            var userId = AbpSession.GetUserId();
            var count = await _userFavoriteStoreRepository.CountAsync(x => x.FavoriteUserId == userId && x.StoreId == form.Id);
            if (count == 0)
            {
                await _userFavoriteStoreRepository.InsertAsync(new UserStoreFavorite
                {
                    FavoriteUserId = userId,
                    StoreId = form.Id
                });
            }
            else
            {
                throw new UserFriendlyException("您已收藏该店铺");
            }
        }
        public async Task NotFavoriteStoreAsync(SingleId<long> form)
        {
            var userId = AbpSession.GetUserId();
            await _userFavoriteStoreRepository.DeleteAsync(x => x.FavoriteUserId == userId && x.StoreId == form.Id);
        }

        public async Task<PagedResultDto<UserStoreFavoriteVO>> GetUserFavoriteStoresAsync(PagedForm form)
        {
            var userId = AbpSession.GetUserId();
            var query = _userFavoriteStoreRepository.GetAll().Where(x => x.FavoriteUserId == userId && !x.store.IsInvalid)
                .OrderByDescending(x => x.CreationTime);
            return await query.ToPagedResultDtoAsync<UserStoreFavorite, UserStoreFavoriteVO>(form, (f, vo) =>
            {
                vo.inStore = f.store;
            });
        }
    }
}
